<?php


namespace App\Http\Controllers\Api;
use App\Http\Controllers\BaseController;
use App\Lib\UploadLib;
use App\Models\Config;
use App\Models\User;
use Illuminate\Http\Request;

class InitController extends BaseController
{
    public function init() {
        $user = $this->getUser();
        $daren_amount = Config::getDarenAmount();
        return $this->success(compact('user', 'daren_amount'));
    }

    public function safe_check(Request $request) {
        $user = $this->getUser();
        $this->validate($request, [
            'type' => 'required',
            'content' => 'required'
        ]);
        $input = $request->input();
        try {
            if ($user->platform == User::PLATFORM_DY) {
                $app = $this->ttMini();
                if ($input['type'] == 'file')
                    $result = $app->content_security->image($input['content'], ['porn', 'politics', 'ad', 'disgusting']);
                else
                    $result = $app->content_security->text($input['content']);

                $predicts = $result['data'][0]['predicts'];
                $hit = false;
                foreach ($predicts as $val) {
                    if ($val['hit']) {
                        $hit = true;
                        break;
                    }
                }
            } else {
                $app = $this->miniProgram();
                if ($input['type'] == 'file') {
                    $url = $this->downloadImage($input['content']);
                    $result = $app->content_security->checkImage($url);
                    unlink($url);
                }
                else
                    $result = $app->content_security->checkText($input['content']);

                $predicts = $result['errcode'];
                $hit = false;
                if ($predicts != 0)
                    $hit = true;

            }
        }catch (\Exception $e) {
            \Log::error($e);
            return $this->failed($e->getMessage());
        }
        return $this->success(['hit' => $hit]);
    }

    private function downloadImage($url)
    {
        $path = public_path('./images/');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        $file = curl_exec($ch);
        curl_close($ch);
        $filename = time() . rand(0, 10000);
        $extendsion = pathinfo($url, PATHINFO_EXTENSION) ?: 'jpg';
        $filename .= "." . $extendsion;
        $resource = fopen($path . $filename, 'a');
        fwrite($resource, $file);
        fclose($resource);
        return $path . $filename;
    }

}

